// 简单版
import request from '../../../../utils/request'
Page({
        data: {
                itemyear: [],
                currentYear: new Date().getFullYear(),
                content: '',
                // 当前登录者信息
                login: {
                        id: 8,
                        avatar: '/images/wechat.png',
                        name: '自己'
                },
                receive: {
                        id: 2,
                        avatar: '/images/在线咨询.png',
                        name: '医生'
                },
                // 聊天信息
                chatList: [{
                                id: '2023',
                                content: '一个简单的聊天对话窗口界面',
                                type: 'text',
                                time: '05-02 14:24', // 每隔5分钟记录一次时间
                                sendId: 1,
                                receiveId: 2
                        },
                        {
                                id: '2023',
                                content: '一个简单的聊天对话窗口界面',
                                type: 'text',
                                time: '05-02 14:24', // 每隔5分钟记录一次时间
                                sendId: 2,
                                receiveId: 1
                        },

                ],
        },
        checkDateDifference(str1, str2) {
                const date1 = new Date(str1);
                const date2 = new Date(str2);
                const diffInMs = Math.abs(date1 - date2);
                const diffInMinutes = diffInMs / (1000 * 60);
                console.log("0000000000")
                console.log(diffInMinutes === 5)
                return diffInMinutes === 5;
        },
        onReady(){
                this.scrollToBottom();
        },
        onLoad(option) {
                this.setData({
                        login:{
                                id: wx.getStorageSync('userid'),
                                avatar: wx.getStorageSync('avator'),
                                name: wx.getStorageSync('name')
                        }
                })
                let t = this
                const eventChannel = this.getOpenerEventChannel()

                // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
                eventChannel.on('acceptDataFromOpenerPage', function (data) {
                        console.log('参数', data)
                        t.setData({
                                receive: data
                        }, async () => {
                                await t.getchatmessage(wx.getStorageSync('userid'), data.id)
                        })
                })
                this.scrollToBottom();
               

        },
        // 输入监听
        inputClick(e) {
                this.setData({
                        content: e.detail.value
                })
        },
        // 发送监听
        sendClick() {
                var that = this;
                var list = this.data.chatList;
                // 获取当前时间
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                const seconds = String(now.getSeconds()).padStart(2, '0');
            
             
                // 组装数据
                var msg = {
                       content:this.data.content,
                       receiveId:that.data.receive.id,
                       sendId:wx.getStorageSync('userid'),
                       time:  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
                       type: 'text',
                      
                }
                request({
                        url:'chat/chat',
                        method:'post'
                        ,data:msg,
                        async  success(res){
                                console.log( '插入->',res);
                                await that.getchatmessage(wx.getStorageSync('userid'), that.data.receive.id)
                                that.scrollToBottom();
                                that.setData({
                                        content: ''
                                })
                        }
                })
               
                     
             
        },
        // 滑动到最底部
        scrollToBottom() {
                setTimeout(() => {
                        wx.pageScrollTo({
                                scrollTop: 200000,
                                duration: 3
                        });
                }, 600)
        },
        getchatmessage(userid, doctorid) {
                let t = this
                return new Promise((resolve, reject) => {
                        request({
                                url: 'chat/chat/ChatListByuser',
                                method: 'get',
                                data: {
                                        userid: userid,
                                        doctorid: doctorid
                                },
                                success(res) {
                                        console.log('res->', res.data.data);
                                        t.setData({
                                                chatList: res.data.data
                                        }, () => {
                                                const now = new Date();
                                                const currentYear = now.getFullYear();
                                                const currentDate = now.getDate();
                                                const currentMonth = now.getMonth() + 1;

                                                const newWarmItems = t.data.chatList.map((item, index) => {
                                                        // const compatibleTime = item.time.replace (/-/g, '/');
                                                        // const itemDate = new Date(item.time);
                                                        const itemDate = new Date(item.time.replace (/-/g, '/'));
                                                        if (index != 0) {

                                                                const fit = new Date(t.data.chatList[index - 1].time.replace (/-/g, '/'));
                                                                const diffInMs = Math.abs(fit - itemDate);
                                                                const diffInMinutes = diffInMs / (1000 * 60);

                                                                if (diffInMinutes <= 5) {
                                                                        item = null
                                                                } else {

                                                                        const itemYear = itemDate.getFullYear();
                                                                        const itemMonth = itemDate.getMonth() + 1;
                                                                        const itemDay = itemDate.getDate();
                                                                        const hours = String(itemDate.getHours()).padStart(2, '0');
                                                                        const minutes = String(itemDate.getMinutes()).padStart(2, '0');
                                                                        if (itemYear === currentYear && itemMonth === currentMonth && itemDay === currentDate) {
                                                                                item = `${hours}:${minutes}`;
                                                                        } else if (itemYear === currentYear) {
                                                                                item = `${itemMonth}月${itemDay}日 ${hours}:${minutes}`;
                                                                        } else {
                                                                                // item = item.time;
                                                                                item=`${itemYear}年${itemMonth}月${itemDay}日 ${hours}:${minutes}`
                                                                        }
                                                                }
                                                        } else {
                                                                const itemYear = itemDate.getFullYear();
                                                                const itemMonth = itemDate.getMonth() + 1;
                                                                const itemDay = itemDate.getDate();
                                                                const hours = String(itemDate.getHours()).padStart(2, '0');
                                                                const minutes = String(itemDate.getMinutes()).padStart(2, '0');
                                                                if (itemYear === currentYear && itemMonth === currentMonth && itemDay === currentDate) {
                                                                        item = `${hours}:${minutes}`;
                                                                } else if (itemYear === currentYear) {
                                                                        item = `${itemMonth}月${itemDay}日 ${hours}:${minutes}`;
                                                                } else {
                                                                        // item = item.time;
                                                                        item=`${itemYear}年${itemMonth}月${itemDay}日 ${hours}:${minutes}`
                                                                }
                                                        }
                                                        return item;
                                                });
                                                t.setData({
                                                        itemyear: newWarmItems
                                                }, () => {
                                                        resolve(1)
                                                });

                                        })
                                }
                        })
                })

        },
      //弹窗
      showPopup(e){
              let that=this
              console.log( 'e->',e.currentTarget.dataset.id);
        wx.showModal({
                title: '提示',
                content: '撤回此条消息!!',
                success (res) {
                  if (res.confirm) {
                    console.log('用户点击确定',res)
                    request({
                            url:'chat/chat'
                            ,method:'put'
                            ,data:{
                                    id:e.currentTarget.dataset.id,
                                    type:'custom'
                            },
                          async  success(){
                                await that.getchatmessage(wx.getStorageSync('userid'), that.data.receive.id)
                                that.scrollToBottom();
                            }
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
              
      }

})